package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.camera.kit.filter.customfilter.CartoonFilter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityComicCameraBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.ProgressConvertUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WorkPathUtil;

public class ComicCameraActivity extends BaseAc<ActivityComicCameraBinding> {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private float myBrightness = 1;//亮度
    private CameraOptions mCameraOptions;
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;
    private boolean isShowBrightness = false;//是否显示亮度
    private boolean isCartoon = false;//是否开启卡通滤镜

    @Override
    protected int onCreate() {
        return R.layout.activity_comic_camera;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.ivCameraBrightness.setOnClickListener(this);
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.tvCameraPicture.setOnClickListener(this);
        mDataBinding.tvCameraVideo.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraFilter.setOnClickListener(this);
        mDataBinding.ivCameraPicture.setOnClickListener(this);

        mDataBinding.sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mCameraOptions != null) {
                    float exposureMinValue = mCameraOptions.getExposureCorrectionMinValue();
                    float exposureMaxValue = mCameraOptions.getExposureCorrectionMaxValue();
                    float value = ProgressConvertUtil.progress2value(progress, exposureMinValue, exposureMaxValue,
                            seekBar.getMax());
                    mDataBinding.cameraView.setExposureCorrection(value);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mHandler = new Handler();
        mRecordTime = 0;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraFlash://闪光灯
                openFlash();
                break;
            case R.id.ivCameraBrightness://亮度
                showBrightness();
                break;
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.tvCameraPicture://拍摄图片模式
                isShoot = false;
                mDataBinding.llVideoLog.setVisibility(View.GONE);
                mDataBinding.tvCameraPicture.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.VISIBLE);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.apaizhao);
                mDataBinding.tvCameraMode.setText(R.string.shoot_picture);
                mDataBinding.cameraView.setMode(Mode.PICTURE);
                break;
            case R.id.tvCameraVideo://拍摄视频模式
                getRecordPermission();
                break;
            case R.id.ivCameraStart://开始拍摄
                startShot();
                break;
            case R.id.ivCameraFilter://切换滤镜
                openFilter();
                break;
            case R.id.ivCameraPicture://本地图片
                getPicPermission();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    private void getRecordPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_record_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                isShoot = true;
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.tvCameraPicture.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.INVISIBLE);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.aluzhiship);
                mDataBinding.tvCameraMode.setText(R.string.shoot_video);
                mDataBinding.cameraView.setMode(Mode.VIDEO);
                mDataBinding.cameraView.setAudio(Audio.ON);
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    private void getPicPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO).reqPermissionDesc(getString(R.string.get_camera_pic_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(AlbumActivity.class);
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                mCameraOptions = options;
            }

            @Override
            public void onCameraClosed() {
                mCameraOptions = null;
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
                mCameraOptions = null;
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        //去到对应结果界面
                        PreviewActivity.resultImg = bitmap;
                        startActivity(PreviewActivity.class);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.llCameraType.setVisibility(View.VISIBLE);
                mDataBinding.llVideoLog.setVisibility(View.GONE);
                mDataBinding.ivCameraStart.setImageResource(R.drawable.aluzhiship);
                mDataBinding.tvVideoNum.setText("00:00");
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                //获取视频 去到预览界面
//                PreviewActivity.isVideo = true;
//                PreviewActivity.resultPath = result.getFile().getPath();
//                startActivity(PreviewActivity.class);
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
            }
        });
    }

    //开始拍摄
    private void startShot() {
        if (!isShoot) {//照片拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            mDataBinding.cameraView.takePictureSnapshot();
        } else {//视频拍摄
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                String filePath = WorkPathUtil.generateVideoFilePath(null);
                if (filePath != null) {
                    mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                }
            }
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashanguangdg);
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.ashangd);
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //显示亮度
    private void showBrightness() {
        if (isShowBrightness) {
            isShowBrightness = false;
            mDataBinding.ivCameraBrightness.setImageResource(R.drawable.aliangdu);
            mDataBinding.sbBrightness.setVisibility(View.GONE);
        } else {
            isShowBrightness = true;
            mDataBinding.ivCameraBrightness.setImageResource(R.drawable.aliangdk);
            mDataBinding.sbBrightness.setVisibility(View.VISIBLE);
        }
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开卡通滤镜
    private void openFilter() {
        if (isCartoon) {
            isCartoon = false;
            mDataBinding.ivCameraFilter.setImageResource(R.drawable.amanhualvj);
            mDataBinding.cameraView.setFilter(Filters.values()[0].newInstance());
        } else {
            isCartoon = true;
            mDataBinding.ivCameraFilter.setImageResource(R.drawable.azhengchangxiangj);
            mDataBinding.cameraView.setFilter(new CartoonFilter());
        }
    }

    //开始拍摄视频
    private void startRecordTime() {
        mDataBinding.llCameraType.setVisibility(View.GONE);
        mDataBinding.llVideoLog.setVisibility(View.VISIBLE);
        mDataBinding.ivCameraStart.setImageResource(R.drawable.aluzhizhong);
        mRecordTime = 0;
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtils.millis2String(mRecordTime * 1000L, "mm:ss"));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    Glide.with(mContext).load(selectMediaEntities.get(0).getPath()).into(mDataBinding.ivCameraPicture);
                }
            }
        });

    }

}